﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxEditors;
using System.Web.Security;

namespace TireService.Website.Kunde
{
    public partial class Bildata : System.Web.UI.Page
    {

        #region Public Properties

        public int CustomerId
        {
            get
            {
                if (ViewState["_customerid"] != null)
                    return (int)ViewState["_customerid"];
                else
                    return (int)Session["CustomerId"];
            }
            set
            {
                ViewState["_customerid"] = value;
            }
        }

        public int CarId
        {
            get
            {
                if (ViewState["_carid"] != null)
                    return (int)ViewState["_carid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_carid"] = value;
            }
        }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Test propertie
            //this.CustomerId = 10000;

            if (Page.IsPostBack != true)
            {
                ddlCarBrand.DataSource = db.GetCarBrand();
                ddlCarBrand.ValueField = "CarBrandId";
                ddlCarBrand.TextField = "Description";
                ddlCarBrand.DataBind();

                int TodayYear = DateTime.Now.Year;

                for (int i = TodayYear; i > 1969; i--)
                {
                    //DevExpress.Web.ASPxEditors.collect
                    ListEditItem item = new ListEditItem();
                    item.Value = i;
                    item.Text = i.ToString();
                    txtYear.Items.Add(item);
                }               
            }

            BindCustomerCar(db, this.CustomerId);
        }

        /// <summary>
        /// Function that bind customer car to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="CustomerId">Id for customer</param>
        private void BindCustomerCar(TireServiceDB db, int CustomerId)
        {
            // Bind to gridview
            gvCar.DataSource = db.GetCars(CustomerId); 
            gvCar.DataBind();

            //gvCar.ClearSort();
            //gvCar.GroupSummary.Clear();
            //gvCar.GroupBy(gvCar.Columns["CustomerSubscriptionDescription"]);
            //gvCar.ExpandAll();
        }

        /// <summary>
        /// Function that load customer car and displays data in edit form
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="CarId">Id on car</param>
        /// <param name="CustomerId">Id on customer</param>
        private void LoadCar(TireServiceDB db, int CarId, int CustomerId)
        {
            // Set car propertie
            this.CarId = CarId;

            // Load car
            Car car = db.GetCar(CarId, CustomerId);

            if (car != null)
            {
                // Show editform
                pCars.Visible = true;

                txtRegistrationNumber.Text = car.RegistrationNumber;
                ddlCarBrand.Items.FindByValue(car.CarBrandId.ToString()).Selected = true;
                ddlFuelType.Items.FindByValue(car.FuelType.ToString()).Selected = true;
                txtModel.Text = car.Model;
                txtColor.Text = car.Color;
                txtYear.Text = car.Year.ToString();
            }
            else
            {
                throw new ArgumentException("Bil eksistere ikke.");
            }
        }

        /// <summary>
        /// Clear car editform
        /// </summary>
        private void ResetEditCar()
        {
            // Clear car propertie
            this.CarId = 0;

            // Clear form fields
            txtRegistrationNumber.Text = "";
            txtModel.Text = "";
            txtColor.Text = "";
            txtYear.Text = "";

            // Hide editform
            pCars.Visible = false;
        }

        /// <summary>
        /// Button Function that cancel edit of customer car
        /// </summary>
        protected void btnCancelEditCar_Click(object sender, EventArgs e)
        {
            ResetEditCar();
        }

        /// <summary>
        /// Button Function that saves customer car
        /// </summary>
        protected void btnSaveCar_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.CustomerId != 0)
                {
                    TireServiceDB db = new TireServiceDB();

                    Car car = new Car();

                    if (this.CarId != 0)
                    {
                        // Edit/Update existing customer car

                        // Fecth existing customer car
                        car = db.GetCar(this.CarId, this.CustomerId);

                        if (car != null)
                        {
                            car.RegistrationNumber = txtRegistrationNumber.Text;
                            car.CarBrandId = Convert.ToInt32(ddlCarBrand.SelectedItem.Value);
                            car.Model = txtModel.Text;
                            car.Year = Convert.ToInt32(txtYear.Text);
                            car.Color = txtColor.Text;
                        }
                        else
                        {
                            // Customer subscription does not exists
                            throw new ArgumentException("Bil eksistere ikke");
                        }
                    }

                    // Commit changes to database
                    db.SubmitChanges();

                    // Refresh gridview and dropdownlist
                    BindCustomerCar(db, this.CustomerId);

                    // Close db connection
                    db.Dispose();

                    // Reset edit form
                    ResetEditCar();

                    // Show message
                    lMessage.Text = "Bil blev gemt.";
                }
                else
                {
                    // Customer not yet saved
                    throw new ArgumentException("Kunde ikke fundet - bil kan derfor ikke opdateres. Venligst log ud og log ind i systemet igen.");
                }

            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
        }

        #region Gridview Functions

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvCar_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            //// Format UnBoundColumn CustomerSubscriptionDescription: Show subscription description
            //if (e.Column.FieldName == "CustomerSubscriptionDescription")
            //{
            //    // Get subscriptionid
            //    int subscriptionid = Convert.ToInt32(e.GetListSourceFieldValue("SubscriptionId"));

            //    TireServiceDB db = new TireServiceDB();

            //    // Change field value
            //    e.Value = db.GetSubscriptionDescription(subscriptionid);

            //    db.Dispose();
            //}

            // Format UnBoundColumn BrandDescription: Show subscription description
            if (e.Column.FieldName == "BrandDescription")
            {
                // Get brandid
                int brandid = Convert.ToInt32(e.GetListSourceFieldValue("CarBrandId"));

                TireServiceDB db = new TireServiceDB();

                // Change field value
                e.Value = db.GetCarBrandDescription(brandid);

                db.Dispose();
            }

            // Format UnBoundColumn CarStatusDescription: Show car status
            if (e.Column.FieldName == "CarStatusDescription")
            {
                // Get carstatusid
                int carstatusid = Convert.ToInt32(e.GetListSourceFieldValue("CarStatusId"));

                TireServiceDB db = new TireServiceDB();

                // Change field value
                e.Value = db.GetCarStatusDescription(carstatusid);

                db.Dispose();
            }

            // Format UnBoundColumn FuelTypeDescription: Show car fueltype
            if (e.Column.FieldName == "FuelTypeDescription")
            {
                // Get fueltype
                int fueltype = Convert.ToInt32(e.GetListSourceFieldValue("FuelType"));

                if (fueltype == 0)
                {
                    e.Value = "Benzin";
                }
                else
                {
                    e.Value = "Diesel";
                }
            }
        }

        /// <summary>
        /// Gridview function that handles edit selection of customer cars
        /// </summary>
        protected void gvCar_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            if (e.ButtonID == "EditCar")
            {
                try
                {
                    // Get carid
                    object cellCarId = gvCar.GetRowValues(e.VisibleIndex, "CarId");

                    TireServiceDB db = new TireServiceDB();

                    // Go to edit mode
                    LoadCar(db, Convert.ToInt32(cellCarId), this.CustomerId);

                    db.Dispose();
                }
                catch (Exception ex)
                {
                    if ((ex) is ArgumentException)
                    {
                        // User error - arguments not valid - show error message
                        lMessage.Text = ((ArgumentException)ex).Message;
                    }
                    else
                    {
                        // System error - show general error message
                        lMessage.Text = "Fejl opstod - venligst prøv igen";
                    }
                }
            }
        }

        #endregion
    }
}